<template>
  <div class="parking-list">
    <div class="page-header">
      <h2>停车场列表</h2>
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索停车场"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <div class="content">
      <div class="map-container">
        <parking-map
          :parking-lots="parkingLots"
          :center="mapCenter"
          :zoom="mapZoom"
          @select-parking="handleSelectParking"
        />
      </div>

      <div class="list-container">
        <div class="filter-bar">
          <el-radio-group v-model="filterType" @change="handleFilterChange">
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button label="available">有空位</el-radio-button>
            <el-radio-button label="nearby">附近</el-radio-button>
          </el-radio-group>
        </div>

        <el-scrollbar height="calc(100vh - 200px)">
          <div class="parking-list">
            <el-card
              v-for="lot in filteredParkingLots"
              :key="lot.id"
              class="parking-item"
              :class="{ 'selected': selectedParking?.id === lot.id }"
              @click="handleSelectParking(lot.id)"
            >
              <div class="parking-info">
                <h3>{{ lot.name }}</h3>
                <div class="info-row">
                  <span class="label">总车位：</span>
                  <span>{{ lot.totalSpaces }}</span>
                </div>
                <div class="info-row">
                  <span class="label">可用车位：</span>
                  <span :class="{ 'available': lot.availableSpaces > 0 }">
                    {{ lot.availableSpaces }}
                  </span>
                </div>
                <div class="info-row">
                  <span class="label">收费标准：</span>
                  <span>{{ lot.hourlyRate }}元/小时</span>
                </div>
                <div class="info-row">
                  <span class="label">距离：</span>
                  <span>{{ formatDistance(lot.distance) }}</span>
                </div>
              </div>
              <div class="parking-actions">
                <el-button
                  type="primary"
                  :disabled="lot.availableSpaces === 0"
                  @click.stop="startParking(lot)"
                >
                  开始停车
                </el-button>
              </div>
            </el-card>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <!-- 导航组件 -->
    <navigation
      v-if="selectedParking"
      :start-location="userLocation"
      :end-location="selectedParkingLocation"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getParkingLots, startParking } from '@/api/parking'
import { formatDistance } from '@/utils/format'
import ParkingMap from '@/components/map/ParkingMap.vue'
import Navigation from '@/components/map/Navigation.vue'

export default {
  name: 'ParkingList',
  components: {
    ParkingMap,
    Navigation,
    Search
  },
  setup() {
    const router = useRouter()
    const parkingLots = ref([])
    const searchKeyword = ref('')
    const filterType = ref('all')
    const selectedParking = ref(null)
    const userLocation = ref(null)
    const mapCenter = ref({ lng: 120.149506, lat: 30.242853 })
    const mapZoom = ref(14)

    // 获取停车场列表
    const loadParkingLots = async () => {
      try {
        const response = await getParkingLots({
          keyword: searchKeyword.value,
          filter: filterType.value
        })
        parkingLots.value = response
      } catch (error) {
        ElMessage.error('获取停车场列表失败')
      }
    }

    // 获取用户位置
    const getUserLocation = () => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            userLocation.value = {
              lng: position.coords.longitude,
              lat: position.coords.latitude
            }
            mapCenter.value = userLocation.value
          },
          (error) => {
            ElMessage.warning('获取位置信息失败，将使用默认位置')
          }
        )
      }
    }

    // 处理搜索
    const handleSearch = () => {
      loadParkingLots()
    }

    // 处理筛选
    const handleFilterChange = () => {
      loadParkingLots()
    }

    // 处理选择停车场
    const handleSelectParking = (id) => {
      selectedParking.value = parkingLots.value.find(lot => lot.id === id)
    }

    // 开始停车
    const startParking = async (lot) => {
      try {
        await startParking(lot.id)
        ElMessage.success('开始停车成功')
        router.push('/parking/records')
      } catch (error) {
        ElMessage.error(error.message || '开始停车失败')
      }
    }

    // 计算选中的停车场位置
    const selectedParkingLocation = computed(() => {
      if (!selectedParking.value) return null
      return {
        lng: selectedParking.value.longitude,
        lat: selectedParking.value.latitude
      }
    })

    // 过滤后的停车场列表
    const filteredParkingLots = computed(() => {
      return parkingLots.value
    })

    onMounted(() => {
      getUserLocation()
      loadParkingLots()
    })

    return {
      parkingLots,
      searchKeyword,
      filterType,
      selectedParking,
      userLocation,
      mapCenter,
      mapZoom,
      filteredParkingLots,
      handleSearch,
      handleFilterChange,
      handleSelectParking,
      startParking,
      selectedParkingLocation,
      formatDistance
    }
  }
}
</script>

<style scoped>
.parking-list {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-box {
  width: 300px;
}

.content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.map-container {
  flex: 1;
  position: relative;
}

.list-container {
  width: 400px;
  background: white;
  border-left: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
}

.filter-bar {
  padding: 15px;
  border-bottom: 1px solid #dcdfe6;
}

.parking-list {
  padding: 15px;
}

.parking-item {
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.parking-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.parking-item.selected {
  border: 2px solid #409eff;
}

.parking-info h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #303133;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
  color: #606266;
}

.info-row .label {
  color: #909399;
}

.info-row .available {
  color: #67c23a;
  font-weight: bold;
}

.parking-actions {
  margin-top: 10px;
  text-align: right;
}
</style> 